<?php

namespace app\controller;

use app\Log;
use app\model\StationBasic;
use app\model\StationPrice;
use app\model\StationPriceTask;
use app\model\StationTask;
use app\model\SupplierStation;
use think\response\Json;

class Task
{
    public function gas_station(): Json
    {
        $log = new Log("gas_task/auto");
        $data = app(StationTask::class)->where('start_time', '<=', date("Y-m-d H:i:s"))->where('state', 0)->find();
        if (empty($data)) {
            $log->write(['message' => "没有任务"]);
            return json(['ecode' => 0, 'message' => "没有任务"]);
        }
        $model = app(\app\model\Stations::class);
        $oil = app(\app\model\StationOil::class);
        $data->save(['state' => 1]);
        $data->startTrans();
        //获取修改价格的油站列表
        $gas_ids = $model->when(!empty($data['city']) && $data['city'] != 'all', function ($query) use ($data) {
            $city = explode(",", $data['city']);
            $query->whereIn('city', $city);
        })->column("id");
        if (empty($gas_ids)) {
            $log->write(['message' => "没有油站"]);
            $data->save(['state' => 2, 'last_time' => date("Y-m-d H:i:s")]);
            $data->commit();
            return json(['ecode' => 0, 'message' => "没有油站"]);
        }
        //获取油枪价格列表
        $_oil = $oil->when(!empty($data['oil_type']) && $data['oil_type'] != '*', function ($query) use ($data) {
            $query->whereIn('oil_no', explode(",", $data['oil_type']));
        })->whereIn('station_id', $gas_ids)->select()->toArray();
//        dd($_oil);
        if (empty($_oil)) {
            $log->write(['message' => "没有油枪"]);
            $data->save(['state' => 2, 'last_time' => date("Y-m-d H:i:s")]);
            $data->commit();
            return json(['ecode' => 0, 'message' => "没有油枪"]);
        }
        $update = [];
        $its = $data->toArray();
        $its['stations_lst'] = json_decode($its['stations_lst'] ?? "[]", true);
        foreach ($_oil as $value) {
            //计算价格
//            $price = bcmul($value['price_official'], bcdiv($data['price'], 100, 4), 4);
            $rate = round($data['price'] / 100, 4);
            $price = round($value['price_official'] * $rate, 2);
            $its['stations_lst'][] = [
                "station_id" => $value['station_id'],
                "price_official" => $value['price_official'],
                "price_gun" => $value['price_gun'],
                "price_third" => $value['price_third'],
                "oil_no" => $value['oil_no'],
                "id" => $value['id']
            ];
            if ($data['type'] == 1) {
                $value['price_official'] = round($price + $value['price_official'], 2);
                $value['price_gun'] = round($price + $value['price_gun'], 2);
                $value['price_third'] = round($value['price_third'] + $price, 2);
            } else if ($data['type'] == 2) {
                $value['price_official'] = round($value['price_official'] - $price, 2);
                $value['price_gun'] = round($value['price_gun'] - $price, 2);
                $value['price_third'] = round($value['price_third'] - $price, 2);
            }
            $update[] = [
                "id" => $value['id'],
                "price_official" => $value['price_official'],
                "price_gun" => $value['price_gun'],
                "price_third" => $value['price_third'],
            ];
        }
//        dd($update);
        $data['stations_lst'] = json_encode($its['stations_lst'], 320);
        $data->state = 2;
        $data->last_time = date("Y-m-d H:i:s");
        $data->save();
        $oil->saveAll($update);
        $data->commit();
        $log->write(['message' => "成功"]);
        return json(['ecode' => 0, 'message' => "成功"]);
    }

    public function open_station()
    {
        $model = app(SupplierStation::class);
        $model->where('state', 2)->where('start_time', '<=', date("Y-m-d H:i:s"))->update(['state' => 1]);//生效
        $model->where('state', 1)->whereNotNull('end_time')->where('end_time', '<=', date("Y-m-d H:i:s"))->update(['state' => 3]);
    }

    public function settingDefaultPrice(): Json
    {
        //更新油机价
        $data = file_get_contents("./station_config/setting.price.conf");
        $conf = json_decode($data, true);
        if (!empty($conf) && strtotime($conf['start_time']) <= time()) {
            @file_put_contents("./station_config/price.conf", $data);
            @file_put_contents("./station_config/setting.price.conf", "{}");
        }
        return json($conf);
    }

    public function autoTask()
    {
        $model = app(StationPriceTask::class);
        $task = $model->alias("st")->leftjoin('station_price sp', 'sp.oil_id=st.oil_id and sp.sup_id=st.sup_id and sp.station_id=st.sid')->where('st.task_time', '<=', date("Y-m-d H:i:s"))->where('st.state', 1)->where('st.type', '<>', 1)->field("sp.*,st.task_id,st.id st_id,st.price rule_number,st.price_type rule_type,st.price_rule_id rule_price,st.type task_type,st.sid,st.sup_id supplier,st.oil_id oil")->paginate(['list_rows' => 100, 'page' => 1])->toArray();
        $ids = array_values(array_unique(array_column($task['data'], 'st_id')));
        $model->whereIn('id', $ids)->update(['state' => 4]);//执行中
        $update = [];
        if (!empty($task['data'])) {
            foreach ($task['data'] as $value) {
                //获取优惠价格
                $discount = $this->matDis($value);

                $update[] = [
                    "id" => $value['id'] ?? null,
                    "station_id" => $value['station_id'] ?? $value['sid'],
                    "oil_id" => $value['oil_id'] ?? $value['oil'],
                    "office_price" => $value['office_price'] ?? 0,
                    "gun_price" => $value['gun_price'] ?? 0,//油机价格
                    "discount_price" => $discount,
                    "sup_id" => $value['sup_id'] ?? $value['supplier'],
                    "price_type" => $value['rule_type'],
                    "price_rule_id" => $value['rule_price'],
                    "price_rule_rate" => $value['rule_number'],
                    "base_start_time"=>$value['base_start_time'] ?? date("Y-m-d H:i:s"),
                ];
            }
        }
        $model->startTrans();
        app(StationPrice::class)->saveAll($update);
        $model->where('id', 'in', $ids)->update(['state' => 2, "tast_update_time" => date("Y-m-d H:i:s")]);
        $model->commit();
        if (empty($task['has_more'])) {
            //更新油站基础价格
            return redirect("updatePrice");
        }

        return redirect("autoTask");
    }

    public function updatePrice()
    {
        $model = app(StationPrice::class);
        $data = $model->where('office_price', '<=', 0)->paginate(['list_rows' => 100, 'page' => 1])->toArray();
        $update = [];
        if (!empty($data['data'])) {
            foreach ($data['data'] as $value) {
                //获取基础价格
                $base = $model->where('station_id', $value['station_id'])->where('oil_id', $value['oil_id'])->where('sup_id', 0)->find();
                if (empty($base)) continue;
                $base = $base->toArray();
                $value = [
                    "id" => $value['id'],
                    "office_price" => $base['office_price'],
                    "gun_price" => $base['gun_price'],
                    "sup_id" => $value['sup_id'],
                    "price_type" => $value['price_type'],
                    "price_rule_id" => $value['price_rule_id'],
                    "price_rule_rate" => $value['price_rule_rate']
                ];
                $value['discount_price'] = $this->matDis($value);
                $update[] = $value;
            }
        }
        if (!empty($update)) {
            $model->saveAll($update);
        }

        if (!empty($data['has_more'])) {
            return redirect("updatePrice");
        }
    }

    protected function matDis(mixed $value): float|int
    {
        $discount = 0;
        $value['rule_type'] = $value['rule_type'] ?? $value['price_type'];
        $value['rule_price'] = $value['rule_price'] ?? $value['price_rule_id'];
        $value['rule_number'] = $value['rule_number'] ?? $value['price_rule_rate'];
        if ($value['gun_price']) {
            if ($value['rule_type'] == 1 || $value['rule_price'] == 1) {
                //固定定价
                $discount = round($value['gun_price'] - $value['rule_number'], 2);
            } else {
                $money = $value['gun_price'] * (1 - $value['rule_number'] / 100);
                if ($value['rule_price'] == 2) {
                    $discount = round($money, 2);
                } else {
                    $discount = (float)bcmul(ceil($money * 100), 100, 2);
                }
            }
        }
        return $discount;
    }

    public function updateGunPrice()
    {
        $model = app(StationPrice::class);
        $task = app(StationTask::class);
        $station = app(StationBasic::class);
        $data = $task->where('state', 0)->where('start_time', '<=', date("Y-m-d H:i:s"))->paginate(['list_rows' => 100, 'page' => 1])->toArray();
//        //获取油站列表
        $oil_lst = [];
        $ups = [];
        foreach ($data['data'] as $value) {
            //获取当前省份的油站
            $_station = $station->where('province_id', $value['proince'])->column("id");
            if(empty($_station)) continue;
            //获取油站油品
            $oil = $model->where('station_id', 'in', $_station)->where('oil_id', $value['oil_type'])->select()->toArray();
            if(empty($oil)) continue;
            foreach ($oil as $v){
                $v['office_price'] = $value['price'];
                $v['gun_price'] = $value['price'];
                $v['discount_price'] = $this->matDis($v);
                $v['base_start_time'] = date("Y-m-d H:i:s");
                $oil_lst[] = $v;
            }
            $ups[] = ['id'=>$value['id'],'last_time'=>date("Y-m-d H:i:s"),'state'=>2];
        }
        $model->startTrans();
        if(!empty($oil_lst)){
            $model->saveAll($oil_lst);
        }
        if(!empty($ups)){
            $task->saveAll($ups);
        }
        $model->commit();
        if (!empty($data['has_more'])) {
            //更新油站基础价格
            return redirect("updateGunPrice");
        }
        return json($oil_lst);
    }
}
